<?php

namespace App\Http\Controllers\Admin\v1;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Controllers\ApiController;
use App\Models\Customer;
use App\Services\Utils\Guard;
use App\Http\Requests\Admin\v1\CustomerLoginRequest;
use App\Exceptions\ApiAbstractException;
use Illuminate\Support\Facades\Cache;

class CustomerLoginController extends ApiController
{
    const LOGIN_VERIFY_CODE_CACHE_KEY_PREFIX = 'CustomerLogin:';

    public function login(CustomerLoginRequest $request)
    {
        $area_code = $request->get('area_code');
        $phone = $request->get('phone');
        $verify_code = $request->get('verify_code');

        $user = $this->checkGetCustomerByVerifyCode($area_code,
                                                        $phone,
                                                        $verify_code);
        $token = Guard::JWTCustomerLogin($user);

        return $this->response(compact('user', 'token'));

    }

    public function getCustomerInfo(Request $request)
    {
        $user = Guard::customer();

        return $this->response(compact('user'));

    }

    private function checkGetCustomerByVerifyCode(string $area_code,
                                                  string $phone,
                                                  string $verify_code)
    {
        // todo: 验证验证码是否正确
        $cache_code = Cache::pull($this->verifyCodeKey($area_code, $phone));
        $this->checkCanOperate($verify_code === $cache_code, trans('checker.verify_code_error'));
        $customer = Customer::findByAreaCodePhone($area_code, $phone);
        return $customer;
    }

    private function verifyCodeKey(string $area_code, string $phone): string
    {
        return self::LOGIN_VERIFY_CODE_CACHE_KEY_PREFIX . $area_code . $phone;
    }
}
